package com.example.spirngbootbase.filter;

import com.example.spirngbootbase.bean.LoginUser;
import com.example.spirngbootbase.bean.SysUser;
import com.example.spirngbootbase.config.redis.RedisCache;
import com.example.spirngbootbase.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @ClassName JwtAuthenticationTokenFilter
 * @Description TODO
 * @Author mujiechen
 * @Date 2022/7/28
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        //判断空值 hasText：如果里面的值为null,"","   "，那么返回值为false；否则为true
        if (!StringUtils.hasText(token)) {
            //为空时 放行
            filterChain.doFilter(request, response);
            return;
        }
        //不为空，解析token token设置是userId
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            throw new RuntimeException("非法的token");
        }
        //判断redis中是否有该用户 redis 中存储的是SysUser
        LoginUser loginUser = redisCache.getCacheObject("login"+userId);
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }
        //把信息放在SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser.getSysUser(),null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
}
